<template>
  <div class="reception-messages">
    <div class="header">
      <h2>消息中心</h2>
      <div class="header-actions">
        <el-button type="primary" @click="showSendDialog = true">
          <el-icon><Message /></el-icon>
          发送消息
        </el-button>
      </div>
    </div>

    <div class="content">
      <!-- 消息列表 -->
      <div class="message-list">
        <el-card class="message-card">
          <template #header>
            <div class="card-header">
              <span>消息列表</span>
              <div class="filter-actions">
                <el-select v-model="filter.type" placeholder="消息类型" style="width: 120px">
                  <el-option label="全部" value=""></el-option>
                  <el-option label="系统消息" value="system"></el-option>
                  <el-option label="家属消息" value="family"></el-option>
                  <el-option label="护工消息" value="caregiver"></el-option>
                  <el-option label="游客咨询" value="visitor"></el-option>
                </el-select>
                <el-select v-model="filter.status" placeholder="消息状态" style="width: 120px">
                  <el-option label="全部" value=""></el-option>
                  <el-option label="未读" value="unread"></el-option>
                  <el-option label="已读" value="read"></el-option>
                </el-select>
                <el-button type="primary" @click="loadMessages">搜索</el-button>
              </div>
            </div>
          </template>

          <el-table :data="messageList" v-loading="loading">
            <el-table-column type="index" label="序号" width="60" align="center" />
            <el-table-column prop="senderName" label="发送者" width="120" align="center" />
            <el-table-column prop="receiverName" label="接收者" width="120" align="center" />
            <el-table-column prop="messageType" label="消息类型" width="100" align="center">
              <template #default="{ row }">
                <el-tag :type="getMessageTypeTag(row.messageType)">
                  {{ getMessageTypeText(row.messageType) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="title" label="标题" min-width="200" show-overflow-tooltip />
            <el-table-column prop="sendTime" label="发送时间" width="180" align="center">
              <template #default="{ row }">
                {{ formatDateTime(row.sendTime) }}
              </template>
            </el-table-column>
            <el-table-column prop="readStatus" label="状态" width="80" align="center">
              <template #default="{ row }">
                <el-tag :type="row.readStatus === 'read' ? 'success' : 'warning'">
                  {{ row.readStatus === 'read' ? '已读' : '未读' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="120" align="center" fixed="right">
              <template #default="{ row }">
                <el-button link type="primary" @click="viewMessageDetail(row)">
                  查看
                </el-button>
                <el-button link type="danger" @click="deleteMessage(row.id)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <div class="pagination">
            <el-pagination
              v-model:current-page="pagination.current"
              v-model:page-size="pagination.size"
              :total="pagination.total"
              :page-sizes="[10, 20, 50, 100]"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </el-card>
      </div>
    </div>

    <!-- 发送消息对话框 -->
    <el-dialog
      v-model="showSendDialog"
      title="发送消息"
      width="600px"
      :before-close="handleSendDialogClose"
    >
      <el-form :model="sendForm" :rules="sendRules" ref="sendFormRef" label-width="80px">
        <el-form-item label="接收者" prop="receiverType">
          <el-radio-group v-model="sendForm.receiverType" @change="handleReceiverTypeChange">
            <el-radio label="family">家属</el-radio>
            <el-radio label="caregiver">护工</el-radio>
            <el-radio label="all_family">所有家属</el-radio>
            <el-radio label="all_caregiver">所有护工</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="具体接收者" prop="receiverIds" v-if="sendForm.receiverType === 'family' || sendForm.receiverType === 'caregiver'">
          <el-select
            v-model="sendForm.receiverIds"
            multiple
            placeholder="请选择接收者"
            style="width: 100%"
            filterable
          >
            <el-option
              v-for="item in receiverOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="消息标题" prop="title">
          <el-input v-model="sendForm.title" placeholder="请输入消息标题" />
        </el-form-item>

        <el-form-item label="消息内容" prop="content">
          <el-input
            v-model="sendForm.content"
            type="textarea"
            :rows="4"
            placeholder="请输入消息内容"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="showSendDialog = false">取消</el-button>
        <el-button type="primary" @click="sendMessage" :loading="sending">
          发送
        </el-button>
      </template>
    </el-dialog>

    <!-- 消息详情对话框 -->
    <el-dialog
      v-model="showDetailDialog"
      title="消息详情"
      width="500px"
    >
      <div class="message-detail">
        <div class="detail-item">
          <label>发送者：</label>
          <span>{{ currentMessage.senderName }}</span>
        </div>
        <div class="detail-item">
          <label>接收者：</label>
          <span>{{ currentMessage.receiverName }}</span>
        </div>
        <div class="detail-item">
          <label>消息类型：</label>
          <span>{{ getMessageTypeText(currentMessage.messageType) }}</span>
        </div>
        <div class="detail-item">
          <label>发送时间：</label>
          <span>{{ formatDateTime(currentMessage.sendTime) }}</span>
        </div>
        <div class="detail-item">
          <label>标题：</label>
          <span>{{ currentMessage.title }}</span>
        </div>
        <div class="detail-item full-width">
          <label>内容：</label>
          <div class="message-content">{{ currentMessage.content }}</div>
        </div>
      </div>

      <template #footer>
        <el-button @click="showDetailDialog = false">关闭</el-button>
        <el-button type="primary" @click="replyMessage" v-if="currentMessage.senderType !== 'system'">
          回复
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Message } from '@element-plus/icons-vue'
import { getReceptionMessages, sendReceptionMessage, deleteMessageById, markMessageAsRead } from '@/api/message'
import { getFamilies, getCaregivers } from '@/api/reception'

const loading = ref(false)
const sending = ref(false)
const showSendDialog = ref(false)
const showDetailDialog = ref(false)
const sendFormRef = ref()
const receiverOptions = ref([])

// 消息列表数据
const messageList = ref([])
const currentMessage = ref({})

// 筛选条件
const filter = reactive({
  type: '',
  status: ''
})

// 分页
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 发送表单
const sendForm = reactive({
  receiverType: 'family',
  receiverIds: [],
  title: '',
  content: ''
})

// 验证规则
const sendRules = {
  receiverType: [
    { required: true, message: '请选择接收者类型', trigger: 'change' }
  ],
  title: [
    { required: true, message: '请输入消息标题', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入消息内容', trigger: 'blur' }
  ]
}

// 加载消息列表
const loadMessages = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.current,
      size: pagination.size,
      ...filter
    }
    const response = await getReceptionMessages(params)
    messageList.value = response.data.records || []
    pagination.total = response.data.total || 0
  } catch (error) {
    ElMessage.error('加载消息列表失败：' + error.message)
  } finally {
    loading.value = false
  }
}

// 加载接收者选项
const loadReceiverOptions = async () => {
  try {
    if (sendForm.receiverType === 'family') {
      const response = await getFamilies()
      receiverOptions.value = response.data || []
    } else if (sendForm.receiverType === 'caregiver') {
      const response = await getCaregivers()
      receiverOptions.value = response.data || []
    }
  } catch (error) {
    ElMessage.error('加载接收者选项失败：' + error.message)
  }
}

// 接收者类型改变
const handleReceiverTypeChange = () => {
  sendForm.receiverIds = []
  if (sendForm.receiverType === 'family' || sendForm.receiverType === 'caregiver') {
    loadReceiverOptions()
  }
}

// 发送消息
const sendMessage = async () => {
  if (!sendFormRef.value) return
  
  try {
    await sendFormRef.value.validate()
    sending.value = true
    
    const messageData = {
      receiverType: sendForm.receiverType,
      receiverIds: sendForm.receiverType.includes('all') ? [] : sendForm.receiverIds,
      title: sendForm.title,
      content: sendForm.content
    }
    
    await sendReceptionMessage(messageData)
    ElMessage.success('消息发送成功')
    showSendDialog.value = false
    loadMessages()
    resetSendForm()
  } catch (error) {
    if (error.errors) {
      ElMessage.error('请完善表单信息')
    } else {
      ElMessage.error('发送消息失败：' + error.message)
    }
  } finally {
    sending.value = false
  }
}

// 重置发送表单
const resetSendForm = () => {
  sendForm.receiverType = 'family'
  sendForm.receiverIds = []
  sendForm.title = ''
  sendForm.content = ''
}

// 查看消息详情
const viewMessageDetail = async (message) => {
  currentMessage.value = message
  showDetailDialog.value = true
  
  // 标记为已读
  if (message.readStatus === 'unread') {
    try {
      await markMessageAsRead(message.id)
      message.readStatus = 'read'
    } catch (error) {
      console.error('标记消息为已读失败：', error)
    }
  }
}

// 回复消息
const replyMessage = () => {
  showDetailDialog.value = false
  showSendDialog.value = true
  sendForm.receiverType = currentMessage.value.senderType === 'family' ? 'family' : 'caregiver'
  sendForm.receiverIds = [currentMessage.value.senderId]
  sendForm.title = `回复：${currentMessage.value.title}`
}

// 删除消息
const deleteMessage = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除这条消息吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await deleteMessageById(id)
    ElMessage.success('删除成功')
    loadMessages()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败：' + error.message)
    }
  }
}

// 分页处理
const handleSizeChange = (size) => {
  pagination.size = size
  pagination.current = 1
  loadMessages()
}

const handleCurrentChange = (current) => {
  pagination.current = current
  loadMessages()
}

// 对话框关闭处理
const handleSendDialogClose = (done) => {
  ElMessageBox.confirm('确定要关闭吗？未保存的内容将会丢失。', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    resetSendForm()
    done()
  }).catch(() => {})
}

// 工具函数
const getMessageTypeTag = (type) => {
  const typeMap = {
    system: 'info',
    family: 'success',
    caregiver: 'warning',
    visitor: 'danger'
  }
  return typeMap[type] || 'info'
}

const getMessageTypeText = (type) => {
  const typeMap = {
    system: '系统消息',
    family: '家属消息',
    caregiver: '护工消息',
    visitor: '游客咨询'
  }
  return typeMap[type] || '未知类型'
}

const formatDateTime = (dateTime) => {
  if (!dateTime) return '-'
  return new Date(dateTime).toLocaleString('zh-CN')
}

onMounted(() => {
  loadMessages()
})
</script>

<style scoped>
.reception-messages {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header h2 {
  margin: 0;
  color: #303133;
}

.content {
  background: #fff;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.filter-actions {
  display: flex;
  gap: 10px;
  align-items: center;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.message-detail {
  padding: 10px 0;
}

.detail-item {
  display: flex;
  margin-bottom: 15px;
  align-items: flex-start;
}

.detail-item label {
  width: 80px;
  font-weight: bold;
  color: #606266;
  flex-shrink: 0;
}

.detail-item span {
  flex: 1;
  color: #303133;
}

.detail-item.full-width {
  flex-direction: column;
}

.message-content {
  margin-top: 5px;
  padding: 10px;
  background: #f5f7fa;
  border-radius: 4px;
  line-height: 1.6;
  white-space: pre-wrap;
}
</style>
